<?php

declare(strict_types=1);

namespace wym\addons\Command;

use think\console\Input;
use think\console\Output;
use think\helper\Str;
use think\facade\Console;

class Command extends Commands
{
    protected $type = 'Command';

    protected function configure(): void
    {
        parent::configure();
        $this->setName('addons:command')
             ->setDescription('Custom plugin command');
    }

    protected function execute(Input $input, Output $output): void
    {
        $basePath = $this->app->addons->getAddonsPath();
        $plugin   = $input->getArgument('name') ?: '';

        $classname = $this->getClassName($plugin);
        $namespace = trim(implode('\\', array_slice(explode('\\', $classname), 0, -1)), '\\');

        $class      = str_replace($namespace . '\\', '', $classname);
        $pluginPath = $basePath . explode('@', $plugin)[0];
        $this->checkDirBuild($pluginPath);

        $filename = $pluginPath . DIRECTORY_SEPARATOR . Str::lower($this->type) . '.php';
        $info     = $this->type . ':' . str_replace('.php', '', str_replace(root_path(), '', $filename));
        parent::write($filename, function ($content) use ($plugin, $namespace, $class) {
            return str_replace(['{%plugin%}', '{%namespace%}', '{%className%}'], [explode('@', $plugin)[0], $namespace, $class], $content);
        }, $info, $output, $this);
        Console::call('addons:commands', [$plugin]);
    }
}
